#include "draw_trace.h"
#include <mupdf/fitz/context.h>

void draw_trace::draw_page(float resolution,float rotation,fz_rect& mediabox,fz_device* dev,
        int output_format,fz_output * out,fz_context* ctx,fz_page *page,int lowmemory,fz_display_list *list
        ,const char * ocr_language,const char * ocr_datadir,fz_cookie *cookie,int pagenum
        ,fz_buffer* out_buffer,std::vector<std::string>& rets){
    float zoom;
    fz_matrix ctm;
    fz_device *pre_ocr_dev = NULL;
    fz_rect tmediabox;

    zoom = resolution / 72;
    ctm = fz_pre_scale(fz_rotate(rotation), zoom, zoom);
    tmediabox = fz_transform_rect(mediabox, ctm);

    fz_var(pre_ocr_dev);

    fz_try(ctx)
    {
        fz_write_printf(ctx, out, "<page mediabox=\"%g %g %g %g\">\n",
                tmediabox.x0, tmediabox.y0, tmediabox.x1, tmediabox.y1);
        dev = fz_new_trace_device(ctx, out);
        if (output_format == OUT_OCR_TRACE)
        {
            pre_ocr_dev = dev;
            dev = NULL;
            dev = fz_new_ocr_device(ctx, pre_ocr_dev, ctm, mediabox, 1, ocr_language, ocr_datadir, NULL, NULL);
        }
        if (lowmemory)
            fz_enable_device_hints(ctx, dev, FZ_NO_CACHE);
        if (list)
            fz_run_display_list(ctx, list, dev, ctm, fz_infinite_rect, cookie);
        else
            fz_run_page(ctx, page, dev, ctm, cookie);
        fz_close_device(ctx, dev);
        fz_drop_device(ctx, dev);
        dev = NULL;
        fz_close_device(ctx, pre_ocr_dev);
        fz_drop_device(ctx, pre_ocr_dev);
        pre_ocr_dev = NULL;
        fz_write_printf(ctx, out, "</page>\n");
    }
    fz_always(ctx)
    {
        fz_drop_device(ctx, pre_ocr_dev);
        fz_drop_device(ctx, dev);
    }
    fz_catch(ctx)
    {
        fz_rethrow(ctx);
    }
}
